﻿using AutoMapper;
using ERPSystem.Common.Domains.Delivergoods;
using ERPSystem.Common.DTO;
using ERPSystem.Common.Infrastructure.IRepository;
using ERPSystem.Enum.CommonErrorCodes;
using MediatR;

namespace SalesManagementWrite.API.SalesManagementWrites.Deliverynotice
{
    public class ShippingnoteUpdateHandler : IRequestHandler<ShippingnoteUpdateCommand, Result>
    {
        private readonly IMapper mapper;
        private readonly IBaseRepository<Shippingnote> shippingnoteRepository;

        public ShippingnoteUpdateHandler(IBaseRepository<Shippingnote> shippingnoteRepository)
        {
            this.shippingnoteRepository = shippingnoteRepository;
        }

        public async Task<Result> Handle(ShippingnoteUpdateCommand request, CancellationToken cancellationToken)
        {
            var result = new Result() { Code = (int)CommonErrorCode.Updated };

            var shippingnote = await (await shippingnoteRepository.GetAll()).Where(d => d.ShippingnoteId == request.ShippingnoteId).FirstAsync();

            if (shippingnote != null)
            {
                shippingnote.DocumentNumber = request.DocumentNumber;
                shippingnote.Documentdate = request.Documentdate;
                shippingnote.DocumentStatus = request.DocumentStatus;
                shippingnote.BusinessStatus = request.BusinessStatus;
                shippingnote.BusinessType = request.BusinessType;
                shippingnote.Stash = request.Stash;
                shippingnote.Customername = request.Customername;
                shippingnote.Warehouseentry = request.Warehouseentry;
                shippingnote.Deliverydate = request.Deliverydate;
                shippingnote.Consignee = request.Consignee;
                shippingnote.ConsigneePhone = request.ConsigneePhone;
                shippingnote.ConsigneeAddress = request.ConsigneeAddress;
                shippingnote.ConsigneeInfo = request.ConsigneeInfo;
                shippingnote.Freight = request.Freight;
                shippingnote.Handlingcharges = request.Handlingcharges;
                shippingnote.Numberpack = request.Numberpack;
                shippingnote.Quantity = request.Quantity;
                shippingnote.ShippingnoteRemark = request.ShippingnoteRemark;
                shippingnote.ShippingnoteRemark = request.ShippingnoteRemark;

                var res = await shippingnoteRepository.Update(shippingnote);
                if(res>0)
                {
                    result.Msg = "修改成功";
                    result.Code = (int)CommonErrorCode.Success;
                }
                else
                {
                    result.Msg = "修改失败";
                    result.Code = (int)CommonErrorCode.Updated;
                }

            }
            return result;


        }
    }
}
